package com.livesource.client.webservices.project;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.jsonp.client.JsonpRequestBuilder;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.livesource.client.LiveSourceGlobalVariables;
import com.livesource.client.model.project.Project;
import com.livesource.client.webservices.github.RequestGitListFiles;
import com.livesource.client.webservices.subversion.RequestSubversionListFiles;

/**
 * Communicates via REST Web Service
 * 
 * @Architecture
 */
public class RequestGetProject {

	private static String url = "http://jsonpfy.livesourceagile.appspot.com/GetService";

	public static void getJsonpRequest(final String panelSelected,
			final String projectID) {

		JsonpRequestBuilder jsonp = new JsonpRequestBuilder();

		jsonp.setTimeout(10000);

		String urlGet = url + "?kind=Project&ID=" + projectID;

		jsonp.requestObject(urlGet, new AsyncCallback<JavaScriptObject>() {

			public void onFailure(Throwable throwable) {

				System.out.println("Error: " + throwable);
			}

			public void onSuccess(JavaScriptObject feed) {

				JSONObject entry = new JSONObject(feed);

				Project project = ConvertJsonpToProject
						.convertJsonProject(entry);

				LiveSourceGlobalVariables.currentProject = project;

				if (Project.REPOSITORY_TYPE_SUBVERSION.equals(project
						.getRepositoryType())) {

					RequestSubversionListFiles.getJsonpRequest(panelSelected,
							project.getRepositoryURL(), null, null);

				} else if (Project.REPOSITORY_TYPE_GITHUB.equals(project
						.getRepositoryType())) {

					RequestGitListFiles.getJsonpRequest(panelSelected,
							project.getRepositoryURL());
				}
			}
		});
	}
}
